package cc.telecomdigital.tdstock;

import android.app.Activity;
import android.os.Handler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import cc.mango.common.HttpUtils;
import cc.telecomdigital.tdstock.Services.LS_ClientParamMemory;

public class WebViewHelper {
	

	
	public  static  void showAd(Activity activity, final WebView webView, final Runnable ...noNetWorkingAction  ) 
	{
		if( activity == null || webView == null) 
		{
			return;
		}
		
		if (webView != null)
		{
			try
			{
				//-------------default setting-----------------
				webView.getSettings().setJavaScriptEnabled(true);
				webView.getSettings().setBlockNetworkImage(false);
				webView.getSettings().setAppCacheEnabled(false);//no cache to save memory
				//-------------default setting-----------------
				
				
				
				//-------------set default action
				webView.setWebViewClient( new  WebViewClient() 
				{
					
					@Override
				    public boolean shouldOverrideUrlLoading(WebView view, String url) 
					{
				        view.loadUrl(url);   
				        return true;   //don't open a new window to browser the url 
				    }

					@Override
					public void onReceivedError(WebView view, int errorCode,
							String description, String failingUrl) {
						super.onReceivedError(view, errorCode, description, failingUrl);
						
					}
					
				});//-------------set default action
				
				
//				  boolean isProduction = ((ITDLApplication)activity.getApplication()).getEnvironment() == CommonDefn.Environment.Production;
//				  final String adUrl= isProduction  ?  CommonDefn.URL_PRODUCTION_AD : CommonDefn.URL_DEVELOPMENT_AD ;
				  final String adUrl= LS_ClientParamMemory.GetADURLInfo();
				  final Handler  handler = new Handler();
				  new Thread() {
					  public void run() {
						
						  if(HttpUtils.isServiceAvailable(adUrl))
							 {
							  		handler.post(   new Runnable() {
							    	 	public void run() {
							    	 		 webView.loadUrl(adUrl);
							    	 	}
							    	 
							     });
							 } //show ad if the networking is ok
						  else  {
							  if(noNetWorkingAction.length >= 1  && noNetWorkingAction[0] != null) 
							  {
								  	try {
										handler.post( noNetWorkingAction[0]);
									} catch (Exception e) {
										e.printStackTrace();
									}
								  
							  }
							  
							  
						  }// do nothing or do something if the networking is disconnected
					  }
				  }.start();
				
					
				

			}
			catch (Exception e)
			{
				e.printStackTrace();
			}

		}
		
		
		
		
	}
	
	
	

}
